package swardToOffer.struct_3_linkedlist;

/**
 * @Author ChanZany
 * @Date 2021/5/21 16:02
 * @Version 1.0
 * 面试题24：反转链表
 * 题目：定义一个函数，输入一个链表的头结点，反转该链表并输出反转后链表的头结点。
 * 定义三个指针，分别指向当前遍历的节点，它的前一个节点和后一个节点
 * p_pre,p,p_post
 * 当操作p进行反转时(p_pre->p->p_post)
 * p.next = p_pre (p_pre<-p p_post)
 * 然后向后移动
 * p_pre = p
 * p = p_post   (xxxxx<-p_pre[p] p[p_post])
 */
public class ReverseList {
    ListNode reverseList(ListNode head) {
        ListNode reverseHead = null;
        ListNode p = head;
        ListNode p_pre = null;
        ListNode p_post = null;
        while (p != null) {
            p_post = p.next;
            if (p_post == null) reverseHead = p;
            p.next = p_pre;
            p_pre = p;
            p = p_post;
        }
        return reverseHead;
    }

    public static void main(String[] args) {
        ReverseList Main = new ReverseList();
        ListNode head = new ListNode(0);
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(6);
        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        ListNode reverseHead = Main.reverseList(head);
        LinkedListUtils.printLinkedList(reverseHead);
    }
}
